package de.rac.vaadin.framework.ui;
/*******************************************************************************
 * Password validator for edit form's password fields (first password field and confirm password fields)<br>
 * @author Volodymyr Dobryvechir (dobrivecher@yahoo.com)
 * @version 0.2 31.05.2012  <br>
 ******************************************************************************/
import com.vaadin.data.Validator;
import com.oros.db.*;

public class PasswordEditFieldValidator implements Validator {

	private static final long serialVersionUID = 1L;
	private int column1,column2,columnData;
	private AERawItem item;
	private String mdAlgorithm;
	private String noMatchMessage;
    public PasswordEditFieldValidator(int column1,int column2,int columnData,AERawItem item,String mdAlgorithm,String noMatchMessage)
    {
    	this.item = item;
    	this.column1 = column1;
    	this.column2 = column2;
    	this.columnData = columnData;
    	this.mdAlgorithm = mdAlgorithm;
    	this.noMatchMessage=noMatchMessage;
    }
	@Override
	public void validate(Object value) throws InvalidValueException {
		if (!isValid(value)) throw new InvalidValueException(noMatchMessage);
	}
    public void setNoMatchMessage(String noMatchMessage)
    {
    	this.noMatchMessage = noMatchMessage;
    }
	@Override
	public boolean isValid(Object value) {
		String dat1=(String)item.getColumnValue(column1);
		String dat2=(String)item.getColumnValue(column2);
		String dat3=(String)value;
		//System.out.println("Validator: "+dat1+"<>"+dat2+"..."+dat3);
		if (dat1!=null)
		{
			dat1=dat1.trim();
			if (dat1.length()==0) dat1=null;
		}
		if (dat2!=null)
		{
			dat2=dat2.trim();
			if (dat2.length()==0) dat2=null;
		}
		if (dat3!=null)
		{
			dat3=dat3.trim();
			if (dat3.length()==0) dat3=null;
		}
		if (dat2==null)
		{
			return (dat1==null)||(dat3==null);
		}
		if ((dat1==null || !dat2.equals(dat1)) 
			&& (dat3==null || !dat2.equals(dat3))) return false;
		item.setPropertyOfItem(columnData, EncodingUtils.getEncodedPassword(dat2, mdAlgorithm));
		return true;
	}

}
